# -*- coding: utf-8 -*-
import hashlib
import hmac
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'yh55': {  # dwc 支付宝 500～5000
        'API_KEY': '069c7518ebd9b13600faedf3a62181fb6870a3d09bb2acc28c0024b175f5b2fdeeb80fcac8e98e72',
        'Person_Access_Key': '''eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjA2OWM3NTE4ZWJkOWIxMzYwMGZhZWRmM2E2MjE4MWZiNjg3MGEzZDA5YmIyYWNjMjhjMDAyNGIxNzVmNWIyZmRlZWI4MGZjYWM4ZTk4ZTcyIn0.eyJhdWQiOiIxIiwianRpIjoiMDY5Yzc1MThlYmQ5YjEzNjAwZmFlZGYzYTYyMTgxZmI2ODcwYTNkMDliYjJhY2MyOGMwMDI0YjE3NWY1YjJmZGVlYjgwZmNhYzhlOThlNzIiLCJpYXQiOjE1MzU0NDE2MjIsIm5iZiI6MTUzNTQ0MTYyMiwiZXhwIjoxNTY2OTc3NjIyLCJzdWIiOiI4MSIsInNjb3BlcyI6W119.yL8GIZJ8LEMS8nbNbAUqnf0s5bQWUqHg5w4XPd3vy0Gn7l_iGYEqqxfDG8BPsKWNvQkfNY6VDB8jsBExTGCuHO69Fp5lwRLiX0AsHi8rDAu3KCMR29nJdWun2sFo7lgOH1QwBWbAp4FsUZpWlJbkiwsnxj38HCZqLYkHmVus0Ig7T5WM58lLfUYJgYWZd9UozHTq5zgWNdftcNVXBDwJAz8Ab_2mLGKb7CF8eglRTTuMXECdlW8lu5GCtUkJmpJ0miysltoO_4moKsWnrVT07znOqcNRsSSDHuKc28xCq64L3rsVuY1HMkRO31U-UTwgOVLVyrgxTr5BSGg4xzCIGEG-2HCWsFli0RXc-whYTBwNXxCCgP_HKn3-hKFQRXtKeFxiKdT6ZMjYn31kM8E22JVTc2YZ4BUGP9u9LLdNP52GaN59CFQgiSmc2WuzJcEMw2c6lKSnIcPkhFmZALZ9NyJjOhvnq9xrKP8liBgRshpLFdFMVM8Mq57cOg0-mKL5JufCCA3K8Rab7T2AbSVRUNjx9xoWfP8OFIWV-3RoBXzY9NWP0MwoM_Y-WaN0ajfhyxMF_KI3EIvQ9eUqtRrn_kuAVHaa6sDhjqPUPljZPySlMQICaOwkoYDYFBSTNzGusciSNebtYxJJZRVm_abWuunlUmjVh31808ngl0mj5d0''',
        'gateway': 'https://www.365payhub.com/api/v3/pay_qr/h5',
        'query_gateway': 'https://www.365payhub.com/api/pay_status',
    },
    'yhcp55': {  # loki 支付宝 100-5000
        'API_KEY': '48bc5512dafe895e15c7d221bb65e8fbd229d4d25ec4ebd0f895305a075dc605895b4994c4dc4780',
        'Person_Access_Key': '''eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjQ4YmM1NTEyZGFmZTg5NWUxNWM3ZDIyMWJiNjVlOGZiZDIyOWQ0ZDI1ZWM0ZWJkMGY4OTUzMDVhMDc1ZGM2MDU4OTViNDk5NGM0ZGM0NzgwIn0.eyJhdWQiOiIxIiwianRpIjoiNDhiYzU1MTJkYWZlODk1ZTE1YzdkMjIxYmI2NWU4ZmJkMjI5ZDRkMjVlYzRlYmQwZjg5NTMwNWEwNzVkYzYwNTg5NWI0OTk0YzRkYzQ3ODAiLCJpYXQiOjE1NDI5NTcwNjQsIm5iZiI6MTU0Mjk1NzA2NCwiZXhwIjoxNTc0NDkzMDY0LCJzdWIiOiIxNzgiLCJzY29wZXMiOltdfQ.J5_CTUOmlnAvkBGmeFuJirZ4S_n2NegByTlOeUfTphDX6swhAM6_gw4Iuz9lcB_i5ZiDWDuttstEWfN9-25Hrenj4mZkbL3X0FLVq3ui39TP6MzHdoPpJdpR0y81Dbxl15yqb1vwtTbpL3e2f5H45182G8SG1APY3vIk-65BQb8FHm4M1FVOLkS3rovF7FJXqm61Mg0w0_hTwFIwpLOfGNLGM1ktql4S_fLkAB4scj5k6C3nN9SAU8Cx-JNzy8GKTSC0m8vHPMVnZeK8F8yyP6OSgg4uhhUx9PUjp3xzv-JaxI91iWgCywQtHLeRjlTAuJCS4L7OY_g_aYMRTCrDOsPphNJMq2jyfvyTpxobP5BWbkp5AlROKMcKIjHZ0Z8eWex-nlIT1bYDo9fpa2yS9fNmk6OA-IBSXkuvPRs9pUX3UMTgGY-mk4Rgw-_U0I1RhKVyD5eWy_FU51w7v3uZiP6NzKdlYZpJ-xMj_XMyrPxKZQceda-cHoBgV3SdAFHvfesMMDqNtafyLG6oXbYm4r9D1TXy3m3u_QiaqtVQOQhBGUqtE0L2OR5QCn0mErRGAhduwHfeTNkGDvrlkQLECsblmg_lBfnwMmz7q1AM6aqB9ZXigVtJvllJlqoBXhEcKPlErCIZLw16_dhWbeSxUlC-Q0VmrVpHy4QXsrDXPwE''',
        'gateway': 'https://www.365payhub.com/api/v3/pay_qr/h5',
        'query_gateway': 'https://www.365payhub.com/api/pay_status',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_person_access_key(mch_id):
    return APP_CONF[mch_id]['Person_Access_Key']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sha256_sign(key, s):
    return hmac.new(key, s.encode('utf8'), hashlib.sha256).hexdigest()


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sha256_sign(key, s).upper()


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("hub365pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    return 'alipay'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    parameter_dict = OrderedDict((
        ('account', app_id),
        ('payType', _get_pay_type(service)),
        ('payMoney', str(pay_amount)),
        ('ip', _get_device_ip(info)),
        ('notifyURL', '{}/pay/api/{}/hub365pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('orderNo', str(pay.id)),
    ))
    _LOGGER.info("hub365pay create: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    headers['Authorization'] = 'Bearer ' + _get_person_access_key(app_id)
    _LOGGER.info('hub365pay create data, %s, headers: %s', parameter_dict, headers)
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('hub365pay create rsp, %s', response.text)
    return {'charge_info': json.loads(response.text)['redirectURL']}


# 888888
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("hub365pay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('hub365pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['payStatus'])
    trade_no = data['uuid']
    total_fee = float(data['realCharge'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success':
        _LOGGER.info('hub365pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    parameter_dict = OrderedDict((
        ('account', app_id),
        ('orderNo', str(pay_order.id)),
    ))
    _LOGGER.info('hub365pay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    headers['Authorization'] = 'Bearer ' + _get_person_access_key(app_id)
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('hub365pay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['statusCode'])
        total_fee = float(data['realCharge'])
        trade_no = ''

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('hub365pay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
